import axios from 'axios'
const service = axios.create({
  timeout: 3000
})

// request拦截器
service.interceptors.request.use(
  config => {
    config.headers['Authorization'] = uni.getStorageSync('token')
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  async response => {
    if (response.data.code != 0) {
      console.log(response.data.code)
      if(response.data.code === '-999') {
        wx.showToast({
          title: response.data.message,
          icon: 'none',
          duration: 2000,
          success: function () {
            setTimeout(() => {
              uni.navigateTo({
                url: "/pages/login/index",
              });
            }, 2000);
          },
        })
      }else{
        wx.showToast({
          title: response.data.message,
          icon: 'none',
          duration: 2000
        })
      }
      return Promise.reject(response)
    }
    return Promise.resolve(response.data)
  },
  error => {
    wx.showToast({
      title: error.data.message,
      icon: 'none',
      duration: 2000
    })
    return Promise.reject(error)
  }
)

service.defaults.adapter = function (config) {
  return new Promise((resolve, reject) => {
    let settle = require('axios/lib/core/settle')
    let buildURL = require('axios/lib/helpers/buildURL')
    uni.request({
      method: config.method.toUpperCase(),
      url: buildURL(config.url, config.params, config.paramsSerializer),
      header: config.headers,
      data: config.data,
      dataType: config.dataType,
      responseType: config.responseType,
      sslVerify: config.sslVerify,
      complete: function complete(response) {
        response = {
          data: response.data,
          status: response.statusCode,
          errMsg: response.errMsg,
          header: response.header,
          config: config
        }
        settle(resolve, reject, response)
      }
    })
  })
}

export default service
